package com.xidian.zhiancloud.service.equipFacility;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xidian.zhiancloud.dao.*;
import com.xidian.zhiancloud.dao.syset.SysPositionMapper;
import com.xidian.zhiancloud.dao.syset.SysUserMapper;
import com.xidian.zhiancloud.dao.syset.usermanage.OrganizationMapper;
import com.xidian.zhiancloud.dto.equipFacility.EqFacMngDTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.exception.CustomizeException;
import com.xidian.zhiancloud.model.*;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.model.syset.SysPosition;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.qo.equipFacility.EqFacMngQO;
import com.xidian.zhiancloud.util.zyf.StringUtils;
import com.xidian.zhiancloud.vo.equipFacility.DefendStandardVO;
import com.xidian.zhiancloud.vo.equipFacility.EqFacMngDTOVO;
import com.xidian.zhiancloud.vo.equipFacility.EqFacMngVO;
import com.xidian.zhiancloud.vo.equipFacility.OhStandardVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 设备设施管理
 * @Author: 任启亮
 * @Date: 2020/11/11
 */
@Service
public class EqFacMngService extends ServiceImpl<EqFacMngMapper, EqFacMng> implements IService<EqFacMng> {
    @Autowired
    private EqFacMngMapper eqFacMngMapper;
    @Autowired
    private OhStandardMapper ohStandardMapper;
    @Autowired
    private DefendStandardMapper defendStandardMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private DeviceTypeMapper deviceTypeMapper;
    @Autowired
    private SysPositionMapper sysPositionMapper;
    @Autowired
    private DefendTypeMapper defendTypeMapper;
    @Autowired
    private OhTypeMapper ohTypeMapper;
    @Autowired
    private TestRecordMapper testRecordMapper;

    public boolean add(EqFacMngDTO eqFacMngDTO) {
        EqFacMng eqFacMng = eqFacMngDTO.getEqFacMng();
        int result = eqFacMngMapper.insert(eqFacMng);
        if (result == 0) {
            throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
        }
        if(eqFacMngDTO.getOhStandard() != null){
            for (OhStandard ohStandard : eqFacMngDTO.getOhStandard()) {
                ohStandard.setEqFacId(eqFacMngDTO.getEqFacMng().getId());
                int tmp1 = ohStandardMapper.insert(ohStandard);
                if (tmp1 == 0) {
                    throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
                }
            }
        }
        if(eqFacMngDTO.getDefendStandard()!=null){
            for (DefendStandard defendStandard : eqFacMngDTO.getDefendStandard()) {
                defendStandard.setEqFacId(eqFacMngDTO.getEqFacMng().getId());
                int tmp2 = defendStandardMapper.insert(defendStandard);
                if (tmp2 == 0) {
                    throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
                }
            }
        }

        if(eqFacMngDTO.getTestRecords() != null && eqFacMng.getChartEq()==1){
            eqFacMngDTO.getTestRecords().forEach(u -> {
                u.setEqFacMngId(eqFacMngDTO.getEqFacMng().getId());
                int tmp = testRecordMapper.insert(u);
                if (tmp == 0) {
                    throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
                }
            });
        }

        return true;
    }

    public EqFacMngDTOVO getDTOVOById(Long id) {
        EqFacMngDTOVO res = new EqFacMngDTOVO();

        EqFacMng eqFacMng = eqFacMngMapper.selectById(id);
        if (eqFacMng == null) {
            throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
        }
        EqFacMngVO vo = new EqFacMngVO();
        BeanUtils.copyProperties(eqFacMng, vo);
        SysUser creator = sysUserMapper.selectById(eqFacMng.getCreator());
        vo.setCreatorName(creator == null ? "该用户不存在" : creator.getName());
        Organization org = organizationMapper.selectById(eqFacMng.getMngCtrDeptId());
        vo.setDepartmentName(org == null ? "该部门不存在" : org.getName());
        SysPosition pos = sysPositionMapper.selectById(eqFacMng.getPosition());
        vo.setPositionName(pos == null ? "该位置不存在" : pos.getName());
        DeviceType deviceType = deviceTypeMapper.selectById(eqFacMng.getDeviceTypeId());
        vo.setDeviceTypeName(deviceType == null ? "该设备类型不存在" : deviceType.getName());
        String[] ids_s = vo.getMngment().split(",");
        List<String> names = Arrays.stream(ids_s).map( id_s ->{
            SysUser user = sysUserMapper.selectById(id_s);
            return user==null?"该用户已被删除":user.getName();
        }).collect(Collectors.toList());
        vo.setMngmentName(StringUtils.concatStrings(names));

        res.setEqFacMngVO(vo);

        LambdaQueryWrapper<DefendStandard> defendStandardLambdaQueryWrapper = new LambdaQueryWrapper<DefendStandard>();
        defendStandardLambdaQueryWrapper.eq(DefendStandard::getEqFacId, id);
        List<DefendStandard> defendStandardList = defendStandardMapper.selectList(defendStandardLambdaQueryWrapper);
        List<DefendStandardVO> voList1 = new LinkedList<>();
        for (int i = 0; i < defendStandardList.size(); i++) {
            DefendStandardVO vos1 = new DefendStandardVO();
            BeanUtils.copyProperties(defendStandardList.get(i), vos1);
            DefendType defendType = defendTypeMapper.selectById(vos1.getDefendTypeId());
            vos1.setDefendtypes(defendType == null ? "该维护类型不存在" : defendType.getName());
            voList1.add(vos1);
        }
        res.setDefendStandardVOList(voList1);


        LambdaQueryWrapper<OhStandard> ohStandardLambdaQueryWrapper = new LambdaQueryWrapper<OhStandard>();
        ohStandardLambdaQueryWrapper.eq(OhStandard::getEqFacId, id);
        List<OhStandard> ohStandardList = ohStandardMapper.selectList(ohStandardLambdaQueryWrapper);
        List<OhStandardVO> voList2 = new LinkedList<>();
        for (int i = 0; i < ohStandardList.size(); i++) {
            OhStandardVO vos2 = new OhStandardVO();
            BeanUtils.copyProperties(ohStandardList.get(i), vos2);
            OhType ohType = ohTypeMapper.selectById(vos2.getOhTypeId());
            vos2.setOhtypes(ohType == null ? "该检修类型不存在" : ohType.getName());
            voList2.add(vos2);
        }
        res.setOhStandardVOList(voList2);


        LambdaQueryWrapper<TestRecord> query = Wrappers.<TestRecord>lambdaQuery();
        query.eq(TestRecord::getEqFacMngId, id);
        List<TestRecord> testRecords = testRecordMapper.selectList(query);
        res.setTestRecords(testRecords);
        return res;
    }

    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public boolean deleteByIds(Long[] ids) {
        for (Long id : ids) {
            LambdaQueryWrapper<DefendStandard> defendStandardLambdaQueryWrapper = new LambdaQueryWrapper<DefendStandard>();
            defendStandardLambdaQueryWrapper.eq(DefendStandard::getEqFacId, id);
            defendStandardMapper.delete(defendStandardLambdaQueryWrapper);

            LambdaQueryWrapper<OhStandard> ohStandardLambdaQueryWrapper = new LambdaQueryWrapper<OhStandard>();
            ohStandardLambdaQueryWrapper.eq(OhStandard::getEqFacId, id);
            ohStandardMapper.delete(ohStandardLambdaQueryWrapper);

            LambdaQueryWrapper<TestRecord> query = Wrappers.<TestRecord>lambdaQuery();
            query.eq(TestRecord::getEqFacMngId, id);
            testRecordMapper.delete(query);

            int result = eqFacMngMapper.deleteById(id);
            if (result == 0) {
                throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
            }
        }
        return true;
    }

    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public boolean patchById(EqFacMngDTO eqFacMngDTO) {
        EqFacMng eqFacMng = eqFacMngDTO.getEqFacMng();
        int result = eqFacMngMapper.updateById(eqFacMng);
        if (result == 0) {
            throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
        }
        LambdaQueryWrapper<DefendStandard> queryWrapper1 = Wrappers.<DefendStandard>lambdaQuery();
        queryWrapper1.eq(DefendStandard::getEqFacId, eqFacMng.getId());
        defendStandardMapper.delete(queryWrapper1);

        LambdaQueryWrapper<OhStandard> queryWrapper2 = Wrappers.<OhStandard>lambdaQuery();
        queryWrapper2.eq(OhStandard::getEqFacId, eqFacMng.getId());
        ohStandardMapper.delete(queryWrapper2);

        LambdaQueryWrapper<TestRecord> queryWrapper3 = Wrappers.<TestRecord>lambdaQuery();
        queryWrapper3.eq(TestRecord::getEqFacMngId, eqFacMng.getId());
        testRecordMapper.delete(queryWrapper3);

        List<DefendStandard> list1 = eqFacMngDTO.getDefendStandard();
        if(list1!=null){
            list1.forEach(detail -> {
                detail.setEqFacId(eqFacMng.getId());
                int tmp = defendStandardMapper.insert(detail);
                if (tmp == 0) {
                    throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
                }
            });
        }

        List<OhStandard> list2 = eqFacMngDTO.getOhStandard();
        if(list2!=null){
            list2.forEach(detail -> {
                detail.setEqFacId(eqFacMng.getId());
                int tmp = ohStandardMapper.insert(detail);
                if (tmp == 0) {
                    throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
                }
            });
        }

        List<TestRecord> list3 = eqFacMngDTO.getTestRecords();
        if(list3!=null){
            list3.forEach(testRecord -> {
                testRecord.setEqFacMngId(eqFacMng.getId());
                int tmp = testRecordMapper.insert(testRecord);
                if (tmp == 0) {
                    throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
                }
            });
        }

        return true;
    }

    public IPage<EqFacMngVO> getListByQO(EqFacMngQO eqFacMngQO) {
        Page<EqFacMngVO> page = new Page<>(eqFacMngQO.getCurrent(), eqFacMngQO.getSize());
        IPage<EqFacMngVO> ans = eqFacMngMapper.selectByQO(page, eqFacMngQO);
//        for (EqFacMngVO record : ans.getRecords()) {
//            Organization org = organizationMapper.selectById(record.getMngCtrDeptId());
//            record.setDepartmentName(org == null ? "该部门不存在" : org.getName());
//            SysUser creator = sysUserMapper.selectById(record.getCreator());
//            record.setCreatorName(creator == null ? "该用户不存在" : creator.getName());
//            SysPosition pos = sysPositionMapper.selectById(record.getPosition());
//            record.setPositionName(pos == null ? "该位置不存在" : pos.getName());
//            DeviceType deviceType = deviceTypeMapper.selectById(record.getDeviceTypeId());
//            record.setDeviceTypeName(deviceType == null ? "该设备类型不存在" : deviceType.getName());
//        }
        return ans.convert(u -> {
            if (u.getDepartmentName() == null) {
                u.setDepartmentName("该部门不存在");
            }
            if (u.getCreatorName() == null) {
                u.setCreatorName("该用户不存在");
            }
            if (u.getPositionName() == null) {
                u.setPositionName("该位置不存在");
            }
            if (u.getDeviceTypeName() == null) {
                u.setDeviceTypeName("该设备类型不存在");
            }
            return u;
        });
    }
}
